package com.yan;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;

/*
    消息消费者
 */
public class Consumer {

    public static void main(String[] args) throws Exception {
        //从 mq拉消息
//        pullMessage();

        //等待 mq推消息
        pushMessage();
    }


    //从 mq拉消息
    private static void pullMessage() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        //  指定虚拟主机('/' 代指这个服务器) 在url中的转义字符 %2f
        // 交换器协议://用户名:密码@ip:端口/虚拟主机
        factory.setUri("amqp://root:root@1.116.195.238:5672/%2f");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //指定从哪个队列消费消息  是否自动确认消息
        GetResponse response = channel.basicGet(QueueConstants.queueName, true);
        //获取消息体
        byte[] body = response.getBody();
        System.out.println("-------消息体 内容----------- " + new String(body));
        //获取消息属性
//        AMQP.BasicProperties props = response.getProps();


        channel.close();
        connection.close();
    }


    //等待 mq推消息
    private static void pushMessage() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        //  指定虚拟主机('/' 代指这个服务器) 在url中的转义字符 %2f
        // 交换器协议://用户名:密码@ip:端口/虚拟主机
        factory.setUri("amqp://root:root@1.116.195.238:5672/%2f");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //声明一个消息队列 确保MQ有该队列 避免没有该队列消费者启动失败
        channel.queueDeclare(QueueConstants.queueName, true, false, false, null);

        //监听指定队列的消息 一旦有消息推送过来，就调用第一个lambda表达式
        channel.basicConsume(QueueConstants.queueName,
                //接收消息推送的 lambda 表达式
                (consumerTag, message) -> {
                    System.out.println("-----message----" + new String(message.getBody()));
                },
                (consumerTag) -> {
                });

//        channel.close();
//        connection.close();
    }

}
